package tools

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path"
	"runtime"
	"strings"
	"time"
)

const Prefix = "├── "
const ItemPrefix = "│\t└──"
const Exit = "exit"
const GetCloseMessage = "\r收到关闭指令,关闭发信通道!"
const WritingEndMessage = "\r通信结束,关闭发信通道!"
const ReadingEndMessage = "\r通信结束，关闭收信通道!"
const TimeFmt = "2006-01-02 15:04:05"
const TimeFileFmt = "20060102150405"

func Out(a ...interface{}) {
	fmt.Println(a...)
}

func FmtOut(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}

func ItemStdout(name, detail string) {
	fmt.Printf("%-20s %s\n", name, detail)
}

func Log(a ...interface{}) {
	fmt.Print("[", time.Now().Format(TimeFmt), "]")
	Out(a...)
}

func FmtLog(format string, a ...interface{}) {
	FmtOut(format, a...)
}

func IsContainExit(s string) bool {
	if len(s) < len(Exit) {
		return false
	}
	ret := true
	bytes1 := []byte(Exit)
	bytes2 := []byte(s)
	for idx, _ := range bytes1 {
		if bytes1[idx] != bytes2[idx] {
			ret = false
			break
		}
	}
	return ret
}

func IsReturnMessage(s string) bool {
	if s == "\n" || s == "\r\n" {
		return true
	}
	return false
}

func Input(tips string, deleteEnd bool) string {
	// 从标准输入获取命令行
	inputBuffer := make([]byte, 1024)
	if tips != "" {
		fmt.Print(tips)
	}
	n, err := os.Stdin.Read(inputBuffer)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}

	inputString := string(inputBuffer[:n])
	if deleteEnd {
		replace := strings.Replace(inputString, "\r", "", -1)
		return strings.Replace(replace, "\n", "", -1)
	}
	return inputString
}

func IsWindows() bool {
	return runtime.GOOS == "windows"
}

func IsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		return false
	}
	return true

}
func NotCoverPath(base, fileName string) string {
	dstPath := path.Join(base, fileName)
	if !PathExists(dstPath) {
		return dstPath
	}
	idx := strings.LastIndex(fileName, ".")
	if idx == -1 {
		fileName = fmt.Sprintf("%s_%d", fileName, time.Now().UnixMilli())
	} else {
		fileName = fmt.Sprintf("%s_%d%s", fileName[:idx], time.Now().UnixMilli(), fileName[idx:])
	}
	return path.Join(base, fileName)
}

// PathReplaceFile 在同目录生成另一个文件的完整路径
func PathReplaceFile(fileName, samePathFile string) string {
	samePathFile = strings.ReplaceAll(samePathFile, "\\", "/")
	arr := strings.Split(samePathFile, "/")
	arr[len(arr)-1] = fileName
	ret := path.Join(arr...)

	// linux路径需要补一个根路径
	if strings.HasPrefix(samePathFile, "/") {
		return "/" + ret
	} else {
		return ret
	}
}

func SmartSize(size int64) string {
	if size < 1024 {
		return fmt.Sprintf("%v B", size)
	} else {
		return fmt.Sprintf("%v KB", size/1024.0)
	}
}

func Sign() string {
	return fmt.Sprintf("%d tools by zhangfan.", time.Now().Year())
}

func Version() string {
	return fmt.Sprintf("Build 2023/9/14. Version v1.0.0 ©%s", Sign())
}

func OpenUrl(args []string) (err error) {
	if len(args) != 2 {
		return errors.New("参数错误")
	}
	if "windows" == runtime.GOOS {
		return exec.Command(`c:\windows\system32\cmd.exe`, "/c start "+args[1]).Start()
	}
	return errors.New("Unsupported platform " + runtime.GOOS)
}

func DoExit(args []string) (err error) {
	os.Exit(0)
	return nil
}

func CommonTools() []*Option {
	return []*Option{
		&Option{"exit", DoExit, "退出."},
		&Option{"open", OpenUrl, `open <URL> 打开指定URL.`},
	}
}
